﻿// -----------------------------------------------------------------------
// <copyright file="Invert.cs" company="FCIS">
// You are welcome to do whatever you want with the code in this file
// </copyright>
// -----------------------------------------------------------------------

namespace ImagePackage.Core.PixelOperations
{
    using System;
    using Model;
    using Utilities;
    
    /// <summary>
    /// Image invert (not) operation
    /// </summary>
    /// <remarks>
    /// This is a simple Pixel operation
    /// </remarks>
    public class Invert : IOperation
    {
        /// <summary>
        /// The input image to act upon
        /// </summary>
        protected readonly Image InputImage;

        /// <summary>
        /// Initializes a new instance of the <see cref="Invert"/> class.
        /// </summary>
        /// <param name="inputImage">The input image.</param>
        public Invert(Image inputImage)
        {
            this.InputImage = inputImage;
        }

        /// <summary>
        /// Applies the operation.
        /// Requires the input image
        /// </summary>
        /// <returns>
        /// Image object
        /// </returns>
        public virtual Image Apply()
        {
            Logger.Debug("Start applying Invert operation");
            try
            {
                Image buffer = new Image(this.InputImage.Width, this.InputImage.Height);
                for (int i = 0; i < this.InputImage.Width; i++)
                {
                    for (int j = 0; j < this.InputImage.Height; j++)
                    {
                        Pixel oldPixel = this.InputImage[i, j];

                        Pixel newPixel = ~oldPixel;

                        buffer[i, j] = newPixel;
                    }
                }

                return buffer;
            }
            catch (Exception ex)
            {
                Logger.LogException("Something wrong happened in Invert Operation", ex);
                throw;
            }
            finally
            {
                Logger.Debug("Finished applying Invert operation");
            }
        }
    }
}
